package cn.ctyun.ipush.web.controller;

import cn.ctyun.ipush.constant.ResultInfo;
import cn.ctyun.ipush.dto.ResultDto;
import cn.ctyun.ipush.model.LoginModel;
import cn.ctyun.ipush.utils.ConfigUtils;
import cn.ctyun.ipush.utils.DataUtils;
import cn.ctyun.ipush.utils.DateUtils;
import cn.ctyun.ipush.utils.MD5;
import cn.ctyun.ipush.web.user.bo.MenuTreeNode;
import cn.ctyun.ipush.web.user.bo.MenuUserNode;
import cn.ctyun.ipush.web.user.bo.UserModel;
import cn.ctyun.ipush.web.user.constanst.SessionAttributeKeys;
import cn.ctyun.ipush.web.user.service.MenuService;
import cn.ctyun.ipush.web.user.service.UserAdminService;
import com.dexcoder.commons.utils.UUIDUtils;
import com.dexcoder.dal.JdbcDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;


/**
 * Created with IntelliJ IDEA.
 * User: WJ
 * Date: 15-5-6
 * Time: 上午10:37
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping
public class LoginController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private UserAdminService userAdminService;
    @Resource
    private MenuService menuService;

    @Resource
    private JdbcDao jdbcDao;

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView userLogin(HttpServletRequest request) {
        return new ModelAndView("login", null);
    }

    @RequestMapping(value = "main", method = RequestMethod.GET)
    public String mainIndex(HttpServletRequest request) {
        return "main";
    }


    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ModelAndView userLoginCheck(HttpServletRequest request) {
        String email = request.getParameter("email");
        String password = request.getParameter("password");

        UserModel systemUserModel = new UserModel();
        systemUserModel.setUserLoginName(email);
        systemUserModel.setUserPassword(password);
        logger.info("param is systemUser = {}", systemUserModel);
        if (systemUserModel == null) {
            //ModelAndView modelAndView = new ModelAndView();
            Map<String, Object> data = new HashMap<String, Object>();

            data.put("errorMsg", "未知错误，请联系管理员");

            return new ModelAndView("login", data);
        } else {
            if (systemUserModel.getUserLoginName() == null || systemUserModel.getUserLoginName().isEmpty()) {
                //throw new RuntimeException("loginUserName is empty");
                Map<String, Object> data = new HashMap<String, Object>();

                data.put("errorMsg", "用户名为空");

                return new ModelAndView("login", data);
            }
            if (systemUserModel.getUserPassword() == null || systemUserModel.getUserPassword().isEmpty()) {
                //throw new RuntimeException("userPassword is empty");
                Map<String, Object> data = new HashMap<String, Object>();

                data.put("errorMsg", "密码为空");

                return new ModelAndView("login", data);
            }
        }
        System.out.println(DataUtils.getFromBASE64(systemUserModel.getUserPassword()));
        systemUserModel = userAdminService.checkLogin(systemUserModel.getUserLoginName(), MD5.getMD5Code(DataUtils.getFromBASE64(systemUserModel.getUserPassword())));

        if (systemUserModel != null && systemUserModel.getUserModelId() != null) {
            //2000s不做操作就失效
            request.getSession().setAttribute(SessionAttributeKeys.SESSION_ATTR_KEY_USERINFO, systemUserModel);

            //加载菜单---
            //取得这个USER的所有菜单
            //取得这个level=1 的所有主菜单
            //根据father归类
            List<MenuUserNode> userlist = menuService.findByUser(systemUserModel.getUserModelId());
            Map<String, Object> data = new HashMap<String, Object>();
            if (userlist != null && !userlist.isEmpty()) {

                MenuTreeNode menuLevelOne = new MenuTreeNode();
                menuLevelOne.setMenuLevel(1);
                List<MenuTreeNode> mOne = menuService.findAllMenuTree(menuLevelOne);

                if (mOne != null && !mOne.isEmpty()) {

                    Map<MenuTreeNode, List<MenuTreeNode>> map = new LinkedHashMap<MenuTreeNode, List<MenuTreeNode>>();

                    for (MenuTreeNode treeNode : mOne) {
                        List sonlist = new ArrayList();

                        for (MenuUserNode userNode : userlist) {
                            MenuTreeNode m = menuService.findById(userNode.getMenuId());
                            if (m.getParentId().equals(treeNode.getMenuTreeNodeId())) {

                                sonlist.add(m);

                            }

                        }


                        //按照menuNodeTree中的order排序，目标sonList
                        //对sonList 根据order 排序
                        Collections.sort(sonlist, new Comparator<MenuTreeNode>() {

                            /*
                             * int compare(Student o1, Student o2) 返回一个基本类型的整型，
                             * 返回负数表示：o1 小于o2，
                             * 返回0 表示：o1和o2相等，
                             * 返回正数表示：o1大于o2。
                             */
                            public int compare(MenuTreeNode o1, MenuTreeNode o2) {

                                //按照学生的年龄进行升序排列
                                if (o1.getMenuOrder() > o2.getMenuOrder()) {
                                    return 1;
                                }
                                if (o1.getMenuOrder() == o2.getMenuOrder()) {
                                    return 0;
                                }
                                return -1;
                            }
                        });
                        map.put(treeNode, sonlist);
                    }
                    //添加登陆日志到数据库
                    LoginModel loginModel=new LoginModel();
                    loginModel.setLoginModelId(UUIDUtils.getUUID32());
                    loginModel.setBelongType(ConfigUtils.getStringValue("startTaskBelongType"));
                    loginModel.setLoginUserId(systemUserModel.getUserModelId());
                    loginModel.setLoginRealname(systemUserModel.getUserRealname());
                    loginModel.setLoginName(systemUserModel.getUserLoginName());
                    loginModel.setLoginTime(DateUtils.dateToString(new Date()));
                    jdbcDao.save(loginModel);
                    request.getSession().setAttribute("fristMenuMap", map);
                } else {
                    data.put("errorMsg", "没有权限");
                    return new ModelAndView("login", data);
                }


            } else {


                data.put("errorMsg", "没有权限");
                return new ModelAndView("login", data);
            }


            return new ModelAndView("main", null);
        } else {
            //throw new RuntimeException("用户或密码是错误的");
            //throw new RuntimeException("userPassword is empty");
            Map<String, Object> data = new HashMap<String, Object>();

            data.put("errorMsg", "用户名密码错误或没有权限");

            return new ModelAndView("login", data);
        }

    }

    /**
     * 捕获异常执行的方法
     *
     * @return
     */
    @ExceptionHandler(LoginException.class)
    @ResponseBody
    public ResultDto handlerException(Exception ex, HttpServletRequest req) {
        ResultDto resultDto = new ResultDto();
        resultDto.setInfo("用户名或密码错误").setStatus(ResultInfo.failure);
        return resultDto;
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public ModelAndView userLogout(HttpSession session, HttpServletRequest request) {
        if (session.getAttribute("userInfo") != null) {
            session.removeAttribute("userInfo");
        }
        return new ModelAndView("login", null);

    }


}
